package cn.tianyigps.tianyigpsapiv2.dao;

import cn.tianyigps.tianyigpsapiv2.oauth2.context.ClientPrincipal;
import cn.tianyigps.tianyigpsapiv2.param.dto.PageDTO;
import cn.tianyigps.tianyigpspublic.bean.GeoFence;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @Author: LiuHao
 * @Descirption:
 * @Date: 2019/4/3_9:27
 */
@Slf4j
@Repository
public class FenceDao extends BaseDao<GeoFence> {

    private static final String GEO_FENCE_TABLE_NAME = "geoFence";

    @Autowired
    private MongoTemplate mongoTemplate;

    public PageDTO<List<GeoFence>> getGeoFenceList(String group, int page, int limit) {
        Query query = new Query();
        PageDTO pageDTO = new PageDTO(page, limit);
        query.addCriteria(Criteria.where("status").ne("0"));
        if(!this.admin()){
            query.addCriteria(Criteria.where("clientId").is(ClientPrincipal.getClientId()));
        }
        if (!StringUtils.isEmpty(group)) {
            query.addCriteria(Criteria.where("group").is(group));
        }
        long count = mongoTemplate.count(query, GeoFence.class, GEO_FENCE_TABLE_NAME);
        pageDTO.setCount(count);
        query.skip(pageDTO.getSkipNum()).limit(limit);
        List<GeoFence> geoFenceData = mongoTemplate.find(query, GeoFence.class, GEO_FENCE_TABLE_NAME);
        pageDTO.setData(geoFenceData);
        return pageDTO;
    }

}
